package auth

import (
	"context"
	"jinrigaoping/api/superadmin/code"
	"jinrigaoping/pkg/tokenverify"
	"jinrigaoping/pkg/utils"
	"jinrigaoping/rpc/sys/sys"

	"jinrigaoping/api/superadmin/internal/svc"
	"jinrigaoping/api/superadmin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {

	//hashPwd, err := utils.HashPassword(req.Password)
	//if err != nil {
	//	return nil, err
	//}

	userInfo, err := l.svcCtx.SysRpc.SysUserByAccount(l.ctx, &sys.SysUserByAccountReq{Account: req.Account})
	if err != nil {
		return nil, err
	}

	if userInfo == nil {
		return nil, code.AccountOrPasswordError
	}

	if !utils.CheckPasswordHash(req.Password, userInfo.Password) {
		return nil, code.AccountOrPasswordError
	}

	token, err := tokenverify.CreateToken(&tokenverify.TokenUserInfo{
		UserId:     userInfo.Id,
		UserType:   userInfo.UserType,
		PlatformId: 0,
		MerchantId: 0,
	}, l.svcCtx.Config.Auth.AccessExpire, l.svcCtx.Config.Auth.AccessSecret)
	if err != nil {
		return nil, err
	}

	return &types.LoginResp{
		AccessToken:  token,
		AccessExpire: l.svcCtx.Config.Auth.AccessExpire,
	}, nil
}
